<template>
  <div>
    <form action="/">
      <van-search
        v-model="keyword"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="handleClear"
        @input="handleChange"
        @clear="handleClear"
      />
    </form>
    <van-cell-group>
      <van-cell
        :value="item.goods_name"
        v-for="item in goodsList"
        :key="item.goods_id"
        @click="toGoodsDetail(item.goods_id)"
      />
    </van-cell-group>
    <van-cell title="历史记录：" v-show="goodsList.length == 0">
      <!-- 使用 right-icon 插槽来自定义右侧图标 -->
      <template #right-icon>
        <van-icon name="delete" style="line-height: inherit;" @click="clear" />
      </template>
      <template #label>
        <van-tag
          size="large"
          @click="toGoodsList(item)"
          v-for="(item,index) in history"
          :key="index"
        >{{item}}</van-tag>
      </template>
    </van-cell>
  </div>
</template>

<script>
export default {
  data() {
    return {
      keyword: "",
      goodsList: [],
      history: [],
      flag: true
    };
  },
  methods: {
    async getGoodsList() {
      if (this.flag) {
        if (this.keyword.trim().length === 0) return false;
        const { data } = await this.$http.get(`/goods/search`, {
          params: {
            query: this.keyword,
            pagesize: "50"
          }
        });
        if (data.meta.status !== 200) return this.$toast.fail("数据获取失败！");
        this.goodsList = data.message.goods;
      }
    },
    onSearch() {
      if (this.flag) {
        this.getGoodsList();
        if (this.keyword.trim().length !== 0) {
          setTimeout(() => {
            this.history.unshift(this.keyword.trim());
            localStorage.setItem("keyword", JSON.stringify(this.history));
          }, 1000);
        }
        return false;
      }
      this.$router.push(`/pages/goods_list?query=${this.keyword}`);
    },
    handleChange() {
      this.flag = true;
      this.onSearch();
    },
    handleClear() {
      this.keyword = "";
      this.goodsList = [];
    },
    clear() {
      this.history = [];
      localStorage.removeItem("keyword");
    },
    toGoodsList(key) {
      this.keyword = key;
      this.flag = false;
    },
    toGoodsDetail(goodsId) {
      this.$router.push("/pages/goods_detail/" + goodsId);
    }
  },
  created() {
    if (localStorage.getItem("keyword")) {
      this.history = JSON.parse(localStorage.getItem("keyword"));
    }
  },
  watch: {
    keyword: function(item) {
      if (item.length === 0) {
        this.goodsList = [];
      }
    }
  }
};
</script>

<style lang="less" scoped>
.van-tag {
  padding: 5px 10px;
  margin: 0 10px 10px 0px;
}
</style>